package org.example.ttms.entityClass.ticket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import org.example.ttms.entityClass.train.Route;
import org.example.ttms.entityClass.train.Trips;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class Ticket {
    private String ticketId;
    private String tripsId;
    private String seatId;
    private String type;
    private double price;
    private String status = "未售出"; //未售出---已售出---已退票---已出发---已到达
    private String departure;//出发地
    private String destination;//目的地
    private Date goTime;
    private Date arrivalTime;
    private String buyerName;
    //对应车次里的id
    private String id;

    public Ticket() {
    }

    public Ticket(String tripsId, String ticketId, String type, double price, Date goTime) {
        this.ticketId = ticketId;
        this.tripsId = tripsId;
        this.type = type;
        this.price = price;
        this.seatId = ticketId.split("-")[2];
        this.id = goTime + " " + this.tripsId;
    }

    public Ticket(String ticketId, String tripsId, String seatId, String type,
                  double price, String status, String id, String buyerName) {
        this.ticketId = ticketId;
        this.tripsId = tripsId;
        this.seatId = seatId;
        this.type = type;
        this.price = price;
        this.status = status;
        this.id = id;
        this.buyerName = buyerName;
    }

    public StringProperty tripsIdProperty(){
        return new SimpleStringProperty(tripsId);
    }

    public StringProperty ticketIdProperty(){
        return new SimpleStringProperty(ticketId.split("-")[1]+ "-" +ticketId.split("-")[2]);
    }

    public StringProperty seatIdProperty(){
        return new SimpleStringProperty(seatId);
    }

    public StringProperty typeProperty(){
        return new SimpleStringProperty(type);
    }

    public DoubleProperty priceProperty(){
        return new SimpleDoubleProperty(price);
    }

    public StringProperty statusProperty(){
        return new SimpleStringProperty(status);
    }

    public StringProperty departureProperty(){
        return new SimpleStringProperty(departure);
    }

    public StringProperty destinationProperty(){
        return new SimpleStringProperty(destination);
    }

    public StringProperty goTimeProperty(){
        if(goTime == null)
            return new SimpleStringProperty("");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
        return new SimpleStringProperty(simpleDateFormat.format(goTime));
    }

    public StringProperty arrivalTimeProperty(){
        if(arrivalTime == null)
            return new SimpleStringProperty("");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
        return new SimpleStringProperty(simpleDateFormat.format(arrivalTime));
    }

    public StringProperty buyerNameProperty(){
        return new SimpleStringProperty(buyerName);
    }

    public String getTicketId() {
        return ticketId;
    }

    public void setTicketId(String ticketId) {
        this.ticketId = ticketId;
    }

    public String getTripsId() {
        return tripsId;
    }

    public void setTripsId(String tripsId) {
        this.tripsId = tripsId;
    }

    public String getSeatId() {
        return seatId;
    }

    public void setSeatId(String seatId) {
        this.seatId = seatId;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDeparture() {
        return departure;
    }

    public void setDeparture(String departure) {
        this.departure = departure;
    }

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

    public Date getGoTime() {
        return goTime;
    }

    public void setGoTime(Date goTime) {
        this.goTime = goTime;
    }

    public Date getArrivalTime() {
        return arrivalTime;
    }

    public void setArrivalTime(Date arrivalTime) {
        this.arrivalTime = arrivalTime;
    }

    public String getBuyerName() {
        return buyerName;
    }

    public void setBuyerName(String buyerName) {
        this.buyerName = buyerName;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    //添加车票
    public void addTicket(Ticket ticket){
        ObjectMapper objectMapper = new ObjectMapper();
        String file = "src/main/java/org/example/ttms/file/ticket.txt";
        try {
            String jsonString = objectMapper.writeValueAsString(ticket);
            System.out.println("addTicket:"+jsonString);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter
                    (new FileOutputStream(file, true)));
            writer.write(jsonString+"\n");
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //获取所有车票
    public HashMap<String, Ticket> obtainAllTicket(){
        HashMap<String, Ticket> hashMap = new HashMap<>();
        String file = "src/main/java/org/example/ttms/file/ticket.txt";
        try {
            Scanner scan = new Scanner(new FileReader(file));
            while(scan.hasNextLine()){
                String str = scan.nextLine();
                ObjectMapper objectMapper = new ObjectMapper();
                Ticket ticket = objectMapper.readValue(str, Ticket.class);
                hashMap.put(ticket.ticketId, ticket);
            }
        } catch (FileNotFoundException | JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return hashMap;
    }
    //删除指定车次的所有票
    public void delTripsAllTicket(Trips trips){
        HashMap<String, Ticket> hashMap = obtainAllTicket();
        List<Ticket> list = new ArrayList<>();
        for(Map.Entry<String, Ticket> map : hashMap.entrySet()){
            if(!(map.getValue().id.equals(trips.getId()) && map.getValue().tripsId.equals(trips.getTripsId()))){
                list.add(map.getValue());
            }
        }
        storageTicket(FXCollections.observableArrayList(list));
    }
    //储存车票---覆盖
    public void storageTicket(ObservableList<Ticket> observableList){
        ObjectMapper objectMapper = new ObjectMapper();
        String file = "src/main/java/org/example/ttms/file/ticket.txt";
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file)));
            String jsonString = null;
            for(Ticket ticket : observableList){
                jsonString = objectMapper.writeValueAsString(ticket);
                writer.write(jsonString+"\n");
            }
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //获取指定车次的所有票
    public List<Ticket> obtainTripsAllTicket(Trips trips){
        HashMap<String, Ticket> hashMap = obtainAllTicket();
        List<Ticket> list = new ArrayList<>();
        for(Map.Entry<String, Ticket> map : hashMap.entrySet()){
            if(map.getValue().id.equals(trips.getId()) && map.getValue().tripsId.equals(trips.getTripsId())){
                list.add(map.getValue());
            }
        }
        return list;
    }
    //获取指定用户购买的所有票
    public List<Ticket> obtainUserAllTicket(String name){
        HashMap<String, Ticket> hashMap = obtainAllTicket();
        List<Ticket> list = new ArrayList<>();
        for(Map.Entry<String, Ticket> map : hashMap.entrySet()){
            if(map.getValue().getBuyerName() != null && map.getValue().getBuyerName().equals(name)){
                list.add(map.getValue());
            }
        }
        return list;
    }
    //Alert框
    public boolean alert(String str){
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText(str);
        alert.setTitle("");
        alert.getDialogPane().setStyle("-fx-font-size: 18px;");
        Optional<ButtonType> result = alert.showAndWait();

        // 判断用户选择
        return result.isPresent() && result.get() == ButtonType.OK;
    }
}
